import { inject, onMounted } from '@vue/composition-api';

/**
 * 演示页面 mixin
 */
export default function useTemplatePageMixin() {
	const vuex_custom_bar_height = inject('vuex_custom_bar_height_key', null)
	const vuex_status_bar_height = inject('vuex_status_bar_height_key', null)
	const $tn = inject('$tn_key', uni.$tn);

	/**
	 * 点击左上角返回按钮时触发事件
	 * 通过判断当前页面的页面栈信息，是否有上一页进行返回，如果没有则跳转到首页
	 */
	const goBack = () => {
		const pages = getCurrentPages()
		if (pages && pages.length > 0) {
			const firstPage = pages[0]
			if (pages.length === 1 && (!firstPage.route || firstPage.route !== '/pages/index/index')) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			} else {
				uni.navigateBack({
					delta: 1
				})
			}
		} else {
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}
	};

	/**
	 * 跳转到首页
	 */
	const goHome = () => {
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}

	/**
	 * 更新顶部导航栏信息
	 */
	const updateCustomBarInfo = async () => {
		// 获取vuex中的自定义顶栏的高度
		let customBarHeight = vuex_custom_bar_height?.value || 0
		let statusBarHeight = vuex_status_bar_height?.value || 0

		// 如果获取失败则重新获取
		if (!customBarHeight || !statusBarHeight) {
			try {
				const navBarInfo = await $tn.updateCustomBar()
				customBarHeight = navBarInfo.customBarHeight
				statusBarHeight = navBarInfo.statusBarHeight

				$tn.vuex('vuex_status_bar_height', statusBarHeight)
				$tn.vuex('vuex_custom_bar_height', customBarHeight)
			} catch (e) {
				console.error('获取自定义导航栏信息失败:', e)
				setTimeout(() => {
					updateCustomBarInfo()
				}, 10)
				return
			}
		} else {
			console.log('自定义导航栏信息已存在:', customBarHeight, statusBarHeight)
		}
	}

	onMounted(() => {
		updateCustomBarInfo()
	})

	return {
		goBack,
		goHome,
		updateCustomBarInfo
	}
}